import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import 'package:toys_flutter/api/app.dart';
import 'package:toys_flutter/components/RefreshableListView.dart';

class MyRoom extends StatefulWidget {
  const MyRoom({super.key});

  @override
  _MyRoomState createState() => _MyRoomState();
}

class _MyRoomState extends State<MyRoom> {
  List<Map<String, dynamic>> _list = [];
  int page = 1;
  bool isMore = true;

  Future<void> _fetchData() async {
    try {
      var res = await Api.imRoomLists({'page': page});
      if (res['code'] == 1) {
        setState(() {
          if (page == 1) {
            _list = List<Map<String, dynamic>>.from(res['data']['data'] ?? []);
          } else {
            _list.addAll(
                List<Map<String, dynamic>>.from(res['data']['data'] ?? []));
          }
          isMore = res['data']['more'] != 0;
        });
      } else {
        _showError('加载失败，请重试');
      }
    } catch (e) {
      _showError('网络错误，请重试');
    }
  }

  Future<void> onLoadMore() async {
    if (!isMore) return;
    page++;
    await _fetchData();
  }

  Future<void> _refreshData() async {
    page = 1;
    await _fetchData();
  }

  void _showError(String message) {
    TDToast.showIconText(
      message,
      icon: TDIcons.error,
      direction: IconTextDirection.vertical,
      context: context,
    );
  }

  @override
  void initState() {
    super.initState();
    _fetchData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('我的聊天室'),
      ),
      body: RefreshableListView(
        onRefresh: _refreshData,
        children: [
          ..._list
              .map((item) => ListItem(item: item, onCallBack: _refreshData)),
          const SizedBox(height: 20),
          if (!isMore)
            const TDDivider(
              text: '没有更多了',
              alignment: TextAlignment.center,
            ),
          const SizedBox(height: 20),
        ],
      ),
    );
  }
}

class ListItem extends StatefulWidget {
  final Map<String, dynamic> item;
  final Future<void> Function() onCallBack;
  const ListItem({super.key, required this.item, required this.onCallBack});

  @override
  _ListItemState createState() => _ListItemState();
}

class _ListItemState extends State<ListItem> {
  late TextEditingController _titleController;
  late TextEditingController _synopsisController;
  File? _imageFile;

  @override
  void initState() {
    super.initState();
    _titleController = TextEditingController(text: widget.item['title']);
    _synopsisController = TextEditingController(text: widget.item['synopsis']);
    _imageFile =
        widget.item['image'] != null ? File(widget.item['image']) : null;
  }

  Future<void> _pickImage() async {
    final picker = ImagePicker();
    final pickedFile = await picker.pickImage(source: ImageSource.gallery);

    if (pickedFile != null) {
      setState(() {
        _imageFile = File(pickedFile.path);
      });
    }
  }

  void _showEditDialog(BuildContext context, Map<String, dynamic> item) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('编辑项目'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              TextField(
                controller: _titleController,
                decoration: const InputDecoration(labelText: '标题'),
              ),
              const SizedBox(height: 20),
              _imageFile != null
                  ? Image.file(_imageFile!,
                      height: 100, width: 100, fit: BoxFit.cover)
                  : Container(),
              TextButton(
                onPressed: _pickImage,
                child: const Text('上传图片'),
              ),
            ],
          ),
          actions: [
            TextButton(
              style: TextButton.styleFrom(
                backgroundColor: Colors.transparent,
                foregroundColor: Colors.black,
              ),
              child: const Text('取消'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
            TextButton(
              child: const Text('保存'),
              onPressed: () {
                setState(() {
                  item['title'] = _titleController.text;
                  item['synopsis'] = _synopsisController.text;
                });
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    var screenWidth = MediaQuery.of(context).size.width;
    return TDSwipeCell(
      groupTag: 'test',
      right: TDSwipeCellPanel(
        extentRatio: 120 / screenWidth,
        children: [
          TDSwipeCellAction(
            flex: 60,
            backgroundColor: TDTheme.of(context).warningColor4,
            label: '编辑',
            onPressed: (context) {
              _showEditDialog(context, widget.item);
              // TDToast.showText('编辑', context: context);
            },
          ),
          TDSwipeCellAction(
            flex: 60,
            backgroundColor: TDTheme.of(context).errorColor6,
            label: '删除',
            onPressed: (context) {
              // 弹框确认删除
              showDialog(
                  context: context,
                  builder: (context) => AlertDialog(
                        title: const Text('删除'),
                        content: const Text('确认删除吗？'),
                        actions: [
                          TextButton(
                            style: TextButton.styleFrom(
                              backgroundColor: Colors.transparent,
                              foregroundColor: Colors.black,
                            ),
                            child: const Text('取消'),
                            onPressed: () {
                              Navigator.of(context).pop();
                            },
                          ),
                          TextButton(
                            onPressed: () {
                              widget.onCallBack();
                              TDToast.showText('删除成功', context: context);
                              Navigator.of(context).pop();
                            },
                            child: const Text('确定'),
                          ),
                        ],
                      ));
            },
          ),
        ],
      ),
      cell: Column(
        children: [
          ListTile(
            leading: TDImage(
              width: 60,
              height: 60,
              imgUrl: widget.item['image'] ?? 'images/default_avatar.png',
              fit: BoxFit.cover,
              type: TDImageType.circle,
            ),
            title: Row(
              children: [
                Text(
                  widget.item['title'] ?? '',
                  style: const TextStyle(fontSize: 14),
                ),
                const SizedBox(width: 5),
                TDTag(
                  'SN: ${widget.item['id']}',
                  shape: TDTagShape.mark,
                  isLight: true,
                  theme: TDTagTheme.warning,
                  size: TDTagSize.small,
                ),
              ],
            ),
            subtitle: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const SizedBox(height: 5),
                const Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    TDTag(
                      '付费',
                      shape: TDTagShape.mark,
                      isLight: true,
                      theme: TDTagTheme.warning,
                      size: TDTagSize.small,
                    ),
                    SizedBox(width: 10),
                    TDTag(
                      '公开',
                      shape: TDTagShape.mark,
                      isLight: true,
                      theme: TDTagTheme.success,
                      size: TDTagSize.small,
                    ),
                  ],
                ),
                const SizedBox(height: 5),
                Text(
                  widget.item['synopsis'] ?? '',
                  style: const TextStyle(fontSize: 12, color: Colors.black38),
                ),
                const SizedBox(height: 5),
                Text(
                  widget.item['create_time_desc'] ?? '',
                  style: const TextStyle(fontSize: 12, color: Colors.black38),
                ),
              ],
            ),
            trailing: Text(
              '最多${widget.item['people'] ?? 0}人',
              style: const TextStyle(color: Colors.black38),
            ),
          ),
          const TDDivider(),
        ],
      ),
    );
  }
}

void main() {
  runApp(const MaterialApp(
    home: MyRoom(),
  ));
}
